<template>
  <el-row id="goodsAdd">
    <el-tabs type="border-card" v-model="tabCol" @tab-click="retailGoodsAddDelay">
      <el-tab-pane label="编辑基本信息">
        <el-col class="bgk">
          <el-col style="text-align: center;line-height: 60px;width: 105px">商品信息</el-col>
          <el-col style="width: 929px;padding: 10px;border-left: 2px solid #fff">
            <el-form :model="retailGoosEntity" label-width="100px" :rules="retailGoosRules" ref="retailGoosInfo">
              <el-form-item label="商品分组">
                <el-select v-model="retailGoosEntity.goodsGroupId" @change="groupShoose(retailGoosEntity.goodsGroupId)" size="small" placeholder="请选择商品分组" clearable
                           style="width: 140px;">
                  <el-option :label="group.name" :value="group.id" v-for="(group,index) in goodsGroupNameList" :key="index"></el-option>
                </el-select>
                <el-button size="small" plain type="primary" @click="goRetailGroup" v-if="loginType === 1">新增分组</el-button>
              </el-form-item>
              <el-form-item label="商品编码">
                <el-input v-model="retailGoosEntity.goodsCode" :maxlength="maxlength_50" size="small" style="width: 140px;"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-col>
        <el-col class="bgk">
          <el-col class="titleCls">库存/规格</el-col>
          <el-col class="contentCls">
            <el-form :model="retailGoosEntity" label-width="100px" :rules="retailGoosRules" ref="retailGoosGg">
              <el-form-item label="商品规格">
                <el-col style="background-color: white;padding: 10px;">
                  <el-col v-for="(reatil,index) in dynamicTagsList" :key="index">
                    <el-col class="bgk" style="height: 50px;padding: 5px;">
                      <el-select v-model="reatil.ggType" size="small" @change="ggTypeChange(reatil.ggType)" clearable
                                 style="width: 92px;margin-left: 7px;">
                        <el-option label="颜色" value="颜色"></el-option>
                        <el-option label="尺寸" value="尺寸"></el-option>
                        <el-option label="尺码" value="尺码"></el-option>
                        <el-option label="规格" value="规格"></el-option>
                        <el-option label="款式" value="款式"></el-option>
                        <el-option label="净含量" value="净含量"></el-option>
                        <el-option label="套餐" value="套餐"></el-option>
                        <el-option label="容量" value="容量"></el-option>
                        <el-option label="上市时间" value="上市时间"></el-option>
                        <el-option label="系列" value="系列"></el-option>
                        <el-option label="适用" value="适用"></el-option>
                        <el-option label="包装" value="包装"></el-option>
                        <el-option label="口味" value="口味"></el-option>
                        <el-option label="产地" value="产地"></el-option>
                      </el-select>
                      <span class="el-tag el-tag--gray" @click="delDynamicTags(index)"
                            style="color: #8391a5;float: right;margin-right: 10px;background-color: inherit;border-color: transparent"><i class="el-tag__close el-icon-close"></i></span>
                    </el-col>
                    <el-col style="height: 50px;padding: 5px;">
                      <el-tag :key="tag" v-for="tag in reatil.dynamicTags" type="gray" style="margin-right: 2px;"
                              :closable="true" :close-transition="false" @close="handleClose(tag,reatil)">
                        {{tag}}
                      </el-tag>
                      <el-input style="width: 80px;" v-if="reatil.inputVisible" v-model="reatil.inputValue" size="mini"
                                @keyup.enter.native="handleInputConfirm(reatil)" @blur="handleInputConfirm(reatil)" :maxlength="maxlength_20">
                      </el-input>
                      <el-button class="button-new-tag" size="small" @click="showInput(reatil)"
                                 v-if="reatil.ggType !== ''&&!reatil.inputVisible">添加
                      </el-button>
                    </el-col>
                  </el-col>
                  <el-col class="bgk" style="height: 50px;padding: 5px;" v-if="this.dynamicTagsList.length < 3">
                    <el-button size="small" style="margin-left: 7px;" @click="addRetailGg">添加规格项目
                    </el-button>
                  </el-col>
                </el-col>
              </el-form-item>
              <el-form-item label="商品库存" v-if="goodsGgList.length > 0" prop="goodsGg">
                <el-col>
                  <table style="width: 100%;border: 2px solid white">
                    <tr style="text-align: center">
                      <td style="width: 10%" v-if="dynamicTagsList[0] !== undefined && dynamicTagsList[0].dynamicTags.length > 0">{{dynamicTagsList[0].ggType}}</td>
                      <td style="width: 10%" v-if="dynamicTagsList[1] !== undefined && dynamicTagsList[1].dynamicTags.length > 0">{{dynamicTagsList[1].ggType}}</td>
                      <td style="width: 10%" v-if="dynamicTagsList[2] !== undefined && dynamicTagsList[2].dynamicTags.length > 0">{{dynamicTagsList[2].ggType}}</td>
                      <td style="width: 10%">价格（元）</td>
                      <td style="width: 10%">库存</td>
                    </tr>
                    <tr style="text-align: center" v-for="(goodsGg,index) in goodsGgList" :key="index">
                      <td style="width: 10%" :rowspan="col0" v-if='goodsGgList[index].ggOne !== goodsGgList[((index-1)>0?(index-1):0)].ggOne||index===0'>{{goodsGg.ggOne}}</td>
                      <td style="width: 10%" :rowspan="col1" v-if='dynamicTagsList[1] !== undefined && dynamicTagsList[1].dynamicTags.length > 0&&(goodsGgList[index].ggOne === goodsGgList[((index-1)>0?(index-1):0)].ggOne&&goodsGgList[index].ggTwo !== goodsGgList[((index-1)>0?(index-1):0)].ggTwo||index===0)'>{{goodsGg.ggTwo}}</td>
                      <td style="width: 10%" :rowspan="col1" v-else-if='dynamicTagsList[1] !== undefined && dynamicTagsList[1].dynamicTags.length > 0&&(goodsGgList[index].ggOne !== goodsGgList[((index-1)>0?(index-1):0)].ggOne&&goodsGgList[index].ggTwo === goodsGgList[((index-1)>0?(index-1):0)].ggTwo)'>{{goodsGg.ggTwo}}</td>
                      <td style="width: 10%" :rowspan="col1" v-else-if='dynamicTagsList[1] !== undefined && dynamicTagsList[1].dynamicTags.length > 0&&(goodsGgList[index].ggOne !== goodsGgList[((index-1)>0?(index-1):0)].ggOne&&goodsGgList[index].ggTwo !== goodsGgList[((index-1)>0?(index-1):0)].ggTwo)'>{{goodsGg.ggTwo}}</td>
                      <td style="width: 10%" v-if="dynamicTagsList[2] !== undefined && dynamicTagsList[2].dynamicTags.length > 0">{{goodsGg.ggThree}}</td>
                      <td style="width: 10%"><el-input size="small" @change="priceKeyDown()" v-model="goodsGg.price"></el-input></td>
                      <td style="width: 10%"><el-input size="small" @change="stockKeyDown()" v-model="goodsGg.stock"></el-input></td>
                    </tr>
                  </table>
                </el-col>
                <el-col style="margin-top: 10px;">
                  <el-col v-if="!batchShow">
                    <span style="color: #48576a">批量设置：</span>
                    <el-button type="text" @click="batchClick('price')">价格</el-button>
                    <el-button type="text" @click="batchClick('stock')">库存</el-button>
                  </el-col>
                  <el-col v-if="batchShow">
                    <span style="color: #48576a">批量设置：</span>
                    <el-input :maxlength="10" v-model="batchValue" :placeholder="placeholderText" style="width: 120px;"></el-input>
                    <el-button type="text" @click="saveBatch">保存</el-button>
                    <el-button type="text" @click="cancelBatch">取消</el-button>
                  </el-col>
                </el-col>
              </el-form-item>
              <el-form-item label="总库存" prop="stocks">
                <el-input v-model="retailGoosEntity.stocks" size="small" style="width: 120px;"  :disabled="goodsGgList.length > 0"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-col>
        <el-col class="bgk">
          <el-col class="titleCls">商品信息</el-col>
          <el-col class="contentCls">
            <el-form :model="retailGoosEntity" label-width="100px" :rules="retailGoosRules" ref="retailGoos">
              <el-form-item label="商品名称" prop="goodsName">
                <el-input v-model="retailGoosEntity.goodsName" :maxlength="maxlength_50" size="small" style="width: 367px;"></el-input>
              </el-form-item>
              <el-form-item label="价格" prop="price">
                <el-input v-model="retailGoosEntity.price" size="small" style="width: 120px;" :disabled="goodsGgList.length > 0" placeholder="价格"></el-input>
              </el-form-item>
              <el-form-item label="商品图" prop="goodsImgList">
                <el-upload
                  action="/smartLight/web/retailGoods/upload.htm"
                  :data="retailGoodsData"
                  class="upload-demo"
                  :auto-upload="false"
                  ref="upload"
                  accept=".bmp,.jpg,.jpeg,.png,.gif"
                  :on-change="handleChange"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  multiple
                  list-type="picture-card"
                  :http-request="syncUpload"
                  :file-list="retailGoosEntity.goodsImgList">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <div class="el-upload__tip" style="color: red;margin-top:-10px;margin-left: 100px;">* 只能上传bmp, jpg, jpeg, png, gif文件，建议大小660*660，不得超过1M</div>
              <el-form-item style="margin-top:30px;">
                <el-button @click="doNext">下一步</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="编辑商品详情" :disabled="retailGoodsAddBol" @click="doNext" id="detailId">
        <el-col style="color: #8391a5;line-height: 30px;">商品简介(选填，微信分享给好友时会显示这里的文案)</el-col>
        <el-input size="small" placeholder="请输入商品简介" v-model="retailGoosEntity.goodsIntroduce"></el-input>
        <el-col style="color: #8391a5;line-height: 30px;">商品详情：</el-col>
        <quill-editor style="margin-top: 30px;margin-bottom: 10px;min-height: 220px;" ref="myTextEditor" v-model="retailGoosEntity.goodsDetail"
                      :config="editorOption"></quill-editor>
        <span style="color: #ff4949" v-if="retailGoosEntity.goodsDetail === ''">请输入商品详情</span>
        <el-upload
          action="/smartLight/web/retailGoods/uploadDetail.htm"
          :data="goodsDataDetail"
          class="upload-demo"
          :auto-upload="true"
          ref="uploadDetail"
          :show-file-list="false"
          accept=".bmp,.jpg,.jpeg,.png,.gif"
          :on-change="handleChangeDetail"
          :on-success="handleSuccessDetail"
          :on-error="handleError"
          :http-request="syncUpload"
          multiple
          list-type="text">
          <el-button size="small" type="primary" style="display: none;" id="imgInput" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="插入中,请稍候">点击上传</el-button>
          <span scope="tip" class="el-upload__tip"> 只能上传bmp, jpg, jpeg, png, gif文件，建议大小660*660，不得超过1M</span>
        </el-upload>
        <el-col style="margin-top: 15px;">
          <el-radio class="radio" v-model="retailGoosEntity.goodsState" :label="true">上架</el-radio>
          <el-radio class="radio" v-model="retailGoosEntity.goodsState" :label="false">下架</el-radio>
        </el-col>
        <el-col style="margin-top: 20px;">
          <el-button @click="doSave" :loading="saveRetailGoodsLoading">保存</el-button>
        </el-col>
      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>

<script type="text/ecmascript-6">
  import {quillEditor} from 'vue-quill-editor' // 导入quillEditor组件
  import {resetBreads, sessionOut} from '../../smartlight/common/js/util.js'
  export default{
    data () {
      var stocksCheck = (rule, value, callback) => {
        var teg = new RegExp('^\\d+$')
        if (value === '') {
          callback(new Error('请输入库存'))
        } else if (!teg.test(value)) {
          callback(new Error('请输入正确的库存，必须为数字'))
        } else {
          callback()
        }
      }
      var priceCheck = (rule, value, callback) => {
        var teg = new RegExp('^\\d+.?\\d{0,2}$')
        if (this.retailGoosEntity.price === '' || this.retailGoosEntity.price === 0) {
          callback(new Error('请输入价格'))
        } else if (!teg.test(this.retailGoosEntity.price)) {
          callback(new Error('价格必须为数字，小数最多两位'))
        } else {
          callback()
        }
      }
      var goodsGgCheck = (rule, value, callback) => {
        var teg = new RegExp('^\\d+.?\\d{0,2}$')
        if (this.goodsGgList.length > 0) {
          var bolPrice = true
          var bollPrice = true
          var bolStock = true
          var bollStock = true
          for (var count in this.goodsGgList) {
            if (this.goodsGgList[count].price === '' || this.goodsGgList[count].price === '0') {
              bolPrice = false
              break
            }
            if (!teg.test(this.goodsGgList[count].price)) {
              bollPrice = false
              break
            }
            if (this.goodsGgList[count].stock === '') {
              bolStock = false
              break
            }
            if (!teg.test(this.goodsGgList[count].stock)) {
              bollStock = false
              break
            }
          }
          if (!bolPrice) {
            callback(new Error('商品价格不能为空或为0'))
          } else if (!bollPrice) {
            callback(new Error('商品价格必须位数字，小数最多两位'))
          } else if (!bolStock) {
            callback(new Error('商品库存不能为空'))
          } else if (!bollStock) {
            callback(new Error('商品库存必须位数字，小数最多两位'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        batchTag: '',
        batchShow: false,
        batchValue: '',
        placeholderText: '',
        urlPrefix: '',
        editorOption: {},
        retailGoodsData: {retailGoodsId: 0},
        goodsDataDetail: {retailGoodsId: 0},
        removeGoodsImgList: [],
        picCountLimit: 4, // 图片个数上限
        picSizeLimit: 1024 * 1024, // 图片大小上限
        loadPath: '', // 上传图片的文件夹
        ggType: '',
        dynamicTagsList: [],
        tabCol: '',
        loginType: '',
        maxlength_20: 20,
        maxlength_50: 50,
        retailGoodsAddBol: true,
        reatil: {
          dynamicTags: [],
          inputVisible: false,
          inputValue: '',
          ggType: ''
        },
        goodsGgList: [], // 规格集合
        goodsGg: {  // 规格对向
          id: 0,
          goodsId: 0,
          ggTypeOne: '',
          ggOne: '',
          ggTypeTwo: '',
          ggTwo: '',
          ggTypeThree: '',
          ggThree: '',
          price: 0,
          stock: 0
        },
        retailGoosEntity: {
          id: 0,
          goodsGroupId: '',
          goodsGroupName: '',
          goodsState: false,
          goodsCode: '',
          goodsName: '',
          isGG: false,
          price: 0,
          stocks: '',
          goodsSmallImg: '',
          goodsImg: '',
          goodsIntroduce: '',
          goodsDetail: '',
          goodsImgList: []
        },
        retailGoosRules: {
          stocks: [
            {required: true, validator: stocksCheck}
          ],
          goodsName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          goodsGg: [
            {required: true, validator: goodsGgCheck}
          ],
          price: [
            {required: true, validator: priceCheck}
          ],
          goodsImgList: [
            {required: true, type: 'array', message: '请选择图片', trigger: 'blur'},
            {required: true, type: 'array', message: '请选择图片', trigger: 'change'}
          ]
        },
        nextBol: true,
        nextBolInfo: true,
        nextBolGg: true,
        saveRetailGoodsLoading: false,
        goodsGroupNameList: [],
        col0: 0,
        col1: 0,
        uploadCount: 0,
        uploadType: '',
        addRange: [],
        fullscreenLoading: false
      }
    },
    methods: {
      cancelBatch () {
        this.batchShow = false
        this.batchTag = ''
        this.placeholderText = ''
        this.batchValue = ''
      },
      saveBatch () {
        var str = this.infoStr(this.batchTag)
        if (this.batchValue === '') {
          this.$message({
            showClose: true,
            message: '请输入' + str,
            type: 'error'
          })
          return
        }
        var teg = ''
        if (this.batchTag === 'stock') {
          teg = new RegExp('^\\d+$')
          if (!teg.test(this.batchValue)) {
            this.$message({
              showClose: true,
              message: str + '必须为正整数',
              type: 'error'
            })
            return
          }
        } else {
          teg = new RegExp('^\\d+.?\\d{0,2}$')
          if (!teg.test(this.batchValue)) {
            this.$message({
              showClose: true,
              message: str + '小数最多两位',
              type: 'error'
            })
            return
          }
        }
        for (var i in this.goodsGgList) {
          if (this.batchTag === 'price') {
            this.goodsGgList[i].price = this.batchValue
          } else if (this.batchTag === 'stock') {
            this.goodsGgList[i].stock = this.batchValue
          }
        }
        if (this.batchTag === 'price') {
          this.priceKeyDown()
        } else if (this.batchTag === 'stock') {
          this.stockKeyDown()
        }
        this.cancelBatch()
      },
      batchClick (val) {
        this.placeholderText = '请输入' + this.infoStr(val)
        this.batchTag = val
        this.batchShow = true
      },
      infoStr (val) {
        var str = ''
        if (val === 'price') {
          str = '价格'
        } else if (val === 'stock') {
          str = '库存'
        }
        return str
      },
      retailGoodsAddDelay () {
        this.retailGoodsAddBol = !this.checkDoNext()
        if (this.retailGoodsAddBol && this.tabCol === '1') {
          this.tabCol = '0'
        }
      },
      priceKeyDown () {
        this.retailGoosEntity.price = 999999999
        let prlist = []
        for (var count in this.goodsGgList) {
//          if (this.goodsGgList[count].price !== '' && this.goodsGgList[count].price !== '0' && this.goodsGgList[count].price < this.retailGoosEntity.price) {
//            this.retailGoosEntity.price = this.goodsGgList[count].price
//          }
          prlist.push(this.goodsGgList[count].price)
        }
        this.retailGoosEntity.price = Math.min.apply(null, prlist)
        if (this.retailGoosEntity.price === 999999999) {
          this.retailGoosEntity.price = 0
        }
      },
      stockKeyDown (val) {
        var number = 0
        for (var count in this.goodsGgList) {
          number += Number(this.goodsGgList[count].stock)
        }
        this.retailGoosEntity.stocks = number
      },
      groupShoose (id) {
        for (var item in this.goodsGroupNameList) {
          if (this.goodsGroupNameList[item].id === id) {
            this.retailGoosEntity.goodsGroupName = this.goodsGroupNameList[item].name
          }
        }
      },
      doSave () {
        if (this.retailGoosEntity.goodsDetail === '') {
          return
        }
        if (this.retailGoosEntity.goodsGroupId === '') {
          this.retailGoosEntity.goodsGroupId = 0
        }
        this.saveRetailGoodsLoading = true
        if (this.goodsGgList.length > 0) {
          this.retailGoosEntity.isGG = true
        } else {
          this.retailGoosEntity.isGG = false
        }
        var para = {
          retailGoosEntity: this.retailGoosEntity,
          removeGoodsImgList: this.removeGoodsImgList,
          goodsGgList: this.goodsGgList,
          type: this.loginType
        }
        this.$http.post('/smartLight/web/retailGoods/retailGoodsAdd.htm', para).then(response => {
          this.saveRetailGoodsLoading = false
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.retailGoodsData.retailGoodsId = resBody.result.retailGoodsId

            if (this.uploadCount !== 0) this.$refs.upload.submit()
            if (this.retailGoosEntity.goodsImg.indexOf('|') === 0) this.retailGoosEntity.goodsImg = this.retailGoosEntity.goodsImg.substring(1)
            this.$http.post('/smartLight/web/retailGoods/updatePicPath.htm', {id: this.retailGoodsData.retailGoodsId, goodsImg: this.retailGoosEntity.goodsImg}).then((resp) => {
              let resBody = resp.body
              if (resBody.isSuccess === 0) {
                var str = ''
                if (this.dialogTitle === '商品发布') {
                  str = '商品发布成功'
                } else {
                  str = '编辑商品成功'
                }
                this.$message({
                  showClose: true,
                  message: str,
                  type: 'success'
                })
                this.$router.push({path: '/retailGoods'})
              }
            })
          } else if (resBody.isSuccess === 2) {
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      doNext () {
        if (this.checkDoNext()) {
          this.tabCol = '1'
          this.retailGoodsAddBol = false
        } else {
          this.tabCol = '0'
          this.retailGoodsAddBol = true
        }
      },
      checkDoNext () {
        this.$refs.retailGoosInfo.validate((valid) => {
          this.nextBolInfo = valid
        })
        this.$refs.retailGoosGg.validate((valid) => {
          this.nextBolGg = valid
        })
        this.$refs.retailGoos.validate((valid) => {
          this.nextBol = valid
        })
        if (this.nextBolInfo && this.nextBol && this.nextBolGg) {
          return true
        } else {
          return false
        }
      },
      delDynamicTags (number) {
        this.dynamicTagsList.splice(number, 1)
        this.shooseDate()
      },
      ggTypeChange (val) {
        var list = this.dynamicTagsList
        var count = 0
        for (var item in list) {
          if (list[item].ggType === val) {
            count++
            if (count > 1) {
              list[item].ggType = ''
              this.$message({
                showClose: true,
                message: '规格类型不能相同',
                type: 'error'
              })
              return
            }
          }
        }
      },
      addRetailGg () {
        this.reatil = {
          dynamicTags: [],
          inputVisible: false,
          inputValue: '',
          ggType: ''
        }
        this.dynamicTagsList.push(this.reatil)
      },
      // 图片上传成功处理方法
      handleSuccess (resp, f, fl) {
        let r = JSON.parse(this.decode(resp))
        if (r.res !== 0) {
          this.$message({
            showClose: true,
            message: '上传图片异常',
            type: 'error'
          })
        } else {
          this.retailGoosEntity.goodsImg += '|' + r.loadPath + r.fileName
          this.retailGoosEntity.goodsSmallImg += '|' + r.loadPath + r.thumbnailPath
        }
      },
      // 图片上传成功处理方法
      handleSuccessDetail (resp, f, fl) {
        let r = JSON.parse(this.decode(resp))
        if (r.res !== 0) {
          this.$message({
            showClose: true,
            message: '上传图片异常',
            type: 'error'
          })
        } else {
          this.retailGoosEntity.goodsDetail += '<img src="' + this.urlPrefix + r.loadPath + r.fileName + '"/>'
        }
      },
      handleError (err, f, fl) {
        console.log(err, f, fl)
      },
      handlePreview (f, fl) {
        window.open(f.url)
      },
      handleRemove (f, fl) {
        if (fl.length < this.picCountLimit) {
          document.getElementsByClassName('el-upload el-upload--picture-card').item(0).style.display = 'inline-block'
        }
        // 删除goodsImg中相应的值
        this.removeGoodsImg(f)
      },
      removeGoodsImg (f, fl) {
        if (f.url.indexOf('blob:http') <= -1) { // 如果不是选择的图片（是展示的图片）
          let arr = this.str2Arr(this.retailGoosEntity.goodsImg, '\\|') // 将goodsImg转换成数组
          let i = arr.indexOf(f.url.substring(f.url.indexOf(this.loadPath))) // 获取删除的url在arr中的索引
          arr.splice(i, 1) // 删除
          this.retailGoosEntity.goodsImg = this.arr2Str(arr, '|') // 将数组还原为goodsImg字符串
          this.removeGoodsImgList.push(f.url.substring(f.url.indexOf(this.loadPath))) // 将要删除的图片地址存起来，发送到后台删除
        } else { // 如果不是展示的图片（是选择的图片）
          this.uploadCount-- // 上传图片计数减一
        }
        // ygc ---- update ---2017-10-11 15:12:50
        if (this.retailGoosEntity.goodsImgList.length > 0) {
          for (var i = 0; i < this.retailGoosEntity.goodsImgList.length; i++) {
            if (this.retailGoosEntity.goodsImgList[i].name === f.name) {
              this.retailGoosEntity.goodsImgList.splice(i, 1)
            }
          }
        }
        if (this.retailGoosEntity.goodsImgList.length === 0) {
          this.tabCol = '0'
          this.retailGoodsAddBol = true
        }
        // -------end ---------
      },
      // 同步上传
      syncUpload (opts) {
        let formData = new FormData()
        formData.append('file', opts.file)
        formData.append('retailGoodsId', opts.data.retailGoodsId)
        let xhr = (function () {
          if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest()
          } else {
            return new window.ActiveXObject('Microsoft.XMLHttp')
          }
        })()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              opts.onSuccess(xhr.responseText)
            } else {
              opts.onError(xhr.responseText)
            }
          }
        }
        xhr.open('POST', opts.action, false)
//        xhr.setRequestHeader('Content-Type', 'multipart/form-data') // 只能在open后调用 发送multipart/form-data时自动设置
        xhr.send(formData)
      },
      // 选择图片处理方法
      handleChange (f, fl) {
        if (f.size > this.picSizeLimit) {
          fl.splice(fl.length - 1, 1)
          this.$message.error('图片大小不能超过1M')
          return false
        }
        if (fl.length > this.picCountLimit) {
          fl.splice(fl.length - 1, 1)
          this.$message.error('图片数量不能超过' + this.picCountLimit + '张')
          return false
        }
        var img = new Image()
        img.src = f.url
        var _this = this
        img.onload = function () {
          var xs = (img.width >= 375 && img.height >= 375)
          if (!xs) {
            fl.splice(fl.length - 1, 1)
            _this.$message.error('图片像素必须大于375*375')
            return false
          } else {
            if (fl.length === this.picCountLimit) {
              document.getElementsByClassName('el-upload el-upload--picture-card').item(0).style.display = 'none'
            }
            _this.retailGoosEntity.goodsImgList[_this.retailGoosEntity.goodsImgList.length] = f
            _this.uploadCount++
            return true
          }
        }
      },
      // 选择图片处理方法
      handleChangeDetail (f, fl) {
        if (f.size > this.picSizeLimit) {
          fl.splice(fl.length - 1, 1)
          this.$message.error('图片大小不能超过1M')
          return false
        }
        return true
      },
      arr2Str (arr, separator) {
        let str = ''
        for (let i = 0; i < arr.length; i++) {
          str += separator + arr[i]
        }
        return str.substring(1)
      },
      handleClose (tag, val) {
        val.dynamicTags.splice(val.dynamicTags.indexOf(tag), 1)
        this.shooseDate()
      },
      showInput (val) {
        val.inputVisible = true
      },
      handleInputConfirm (val) {
        let inputValue = val.inputValue
        if (inputValue !== undefined && inputValue.trim() !== '') {
          val.dynamicTags.push(inputValue)
          this.shooseDate()
        }
        val.inputVisible = false
        val.inputValue = ''
      },
      shooseDate () {
        var list0 = this.dynamicTagsList[0]
        var list1 = this.dynamicTagsList[1]
        var list2 = this.dynamicTagsList[2]
        this.goodsGgList = []
        this.col0 = 0
        this.col1 = 0
        if (list0 !== undefined && list0.dynamicTags.length > 0) {
          for (var i = 0; i < list0.dynamicTags.length; i++) {
            if (list1 !== undefined && list1.dynamicTags.length > 0) {
              for (var j = 0; j < list1.dynamicTags.length; j++) {
                if (list2 !== undefined && list2.dynamicTags.length > 0) {
                  for (var k = 0; k < list2.dynamicTags.length; k++) {
                    this.goodsGg = {
                      id: 0,
                      goodsId: 0,
                      ggTypeOne: list0.ggType,
                      ggOne: list0.dynamicTags[i],
                      ggTypeTwo: list1.ggType,
                      ggTwo: list1.dynamicTags[j],
                      ggTypeThree: list2.ggType,
                      ggThree: list2.dynamicTags[k],
                      price: 0,
                      stock: 0
                    }
                    this.goodsGgList.push(this.goodsGg)
                  }
                  this.col0 = list1.dynamicTags.length * list2.dynamicTags.length
                  this.col1 = list2.dynamicTags.length
                } else {
                  this.goodsGg = {
                    id: 0,
                    goodsId: 0,
                    ggTypeOne: list0.ggType,
                    ggOne: list0.dynamicTags[i],
                    ggTypeTwo: list1.ggType,
                    ggTwo: list1.dynamicTags[j],
                    ggTypeThree: '',
                    ggThree: '',
                    price: 0,
                    stock: 0
                  }
                  this.goodsGgList.push(this.goodsGg)
                  this.col0 = list1.dynamicTags.length
                }
              }
            } else {
              if (list2 !== undefined && list2.dynamicTags.length > 0) {
                for (var m = 0; m < list2.dynamicTags.length; m++) {
                  this.goodsGg = {
                    id: 0,
                    goodsId: 0,
                    ggTypeOne: list0.ggType,
                    ggOne: list0.dynamicTags[i],
                    ggTypeTwo: '',
                    ggTwo: '',
                    ggTypeThree: list2.ggType,
                    ggThree: list2.dynamicTags[m],
                    price: 0,
                    stock: 0
                  }
                  this.goodsGgList.push(this.goodsGg)
                }
                this.col0 = list2.dynamicTags.length
              } else {
                this.goodsGg = {
                  id: 0,
                  goodsId: 0,
                  ggTypeOne: list0.ggType,
                  ggOne: list0.dynamicTags[i],
                  ggTypeTwo: '',
                  ggTwo: '',
                  ggTypeThree: '',
                  ggThree: '',
                  price: 0,
                  stock: 0
                }
                this.goodsGgList.push(this.goodsGg)
              }
            }
          }
        } else {
          if (list1 !== undefined && list1.dynamicTags.length > 0) {
            for (var a = 0; a < list1.dynamicTags.length; a++) {
              if (list2 !== undefined && list2.dynamicTags.length > 0) {
                for (var b = 0; b < list2.dynamicTags.length; b++) {
                  this.goodsGg = {
                    id: 0,
                    goodsId: 0,
                    ggTypeOne: '',
                    ggOne: '',
                    ggTypeTwo: list1.ggType,
                    ggTwo: list1.dynamicTags[a],
                    ggTypeThree: list2.ggType,
                    ggThree: list2.dynamicTags[b],
                    price: 0,
                    stock: 0
                  }
                  this.goodsGgList.push(this.goodsGg)
                }
                this.col1 = list2.dynamicTags.length
              } else {
                this.goodsGg = {
                  id: 0,
                  goodsId: 0,
                  ggTypeOne: '',
                  ggOne: '',
                  ggTypeTwo: list1.ggType,
                  ggTwo: list1.dynamicTags[a],
                  ggTypeThree: '',
                  ggThree: '',
                  price: 0,
                  stock: 0
                }
                this.goodsGgList.push(this.goodsGg)
              }
            }
          } else {
            if (list2 !== undefined && list2.dynamicTags.length > 0) {
              for (var c = 0; c < list2.dynamicTags.length; c++) {
                this.goodsGg = {
                  id: 0,
                  goodsId: 0,
                  ggTypeOne: '',
                  ggOne: '',
                  ggTypeTwo: '',
                  ggTwo: '',
                  ggTypeThree: list2.ggType,
                  ggThree: list2.dynamicTags[c],
                  price: 0,
                  stock: 0
                }
                this.goodsGgList.push(this.goodsGg)
              }
            }
          }
        }
      },
      str2Arr (str, separator) {
        if (!str) return []
        let reg = new RegExp(separator)
        let arr = str.split(reg)
        return arr
      },
      groupRetail () {
        var para = {
          type: this.loginType
        }
        this.$http.post('/smartLight/web/retailGoodsGroup/getGoodsGroup.htm', para).then(response => {
          var resBody = response.body
          if (resBody.isSuccess === 0) {
            this.goodsGroupNameList = resBody.result
          } else if (resBody.isSuccess === 2) {
            sessionOut(this) // session超时处理
          } else {
            this.$message({
              showClose: true,
              message: resBody.errorMsg,
              type: 'error'
            })
          }
        })
      },
      // 点击图片ICON触发事件
      imgHandler (state) {
        this.addRange = this.$refs.myTextEditor.quill.getSelection()
        if (state) {
          let fileInput = document.getElementById('imgInput')
          fileInput.click() // 加一个触发事件
        }
        this.uploadType = 'image'
      },
      // 跳转到商品分组
      goRetailGroup () {
        this.$router.push({path: 'retailGoodsGroup', query: {pt: 'add'}})
      }
    },
    mounted () {
      resetBreads(this)
      var user = sessionStorage.getItem('user')
      if (user) {
        user = JSON.parse(user)
        this.loginType = user.type
      }
      this.urlPrefix = sessionStorage.getItem('prefix')
      var ftype = this.$route.query.ftype
      if (ftype !== 'add') {
        let id = this.$route.query.id
        this.$http.post('/smartLight/web/retailGoods/getById.htm', {id: id, type: this.loginType}).then(response => {
          var resBody = response.body
          if (resBody.isSuccess === 2) {
            sessionOut(this)
          }
          if (resBody.isSuccess === 1 || resBody.isSuccess === 3) {
            this.$message.error(resBody.errorMsg)
          }
          if (resBody.isSuccess === 0) {
            let entity = resBody.result.retailGoods
            this.goodsGgList = resBody.result.goodsGgList
            this.dynamicTagsList = resBody.result.dynaicList
            this.col0 = resBody.result.col0
            this.col1 = resBody.result.col1
            let arr = this.str2Arr(entity.goodsImg, '\\|')
            let spl = []
            for (let i = 0; i < arr.length; i++) {
              spl.push({name: arr[i], url: this.urlPrefix + arr[i], status: 'success'})
            }
            entity.goodsImgList = spl
            this.retailGoosEntity = entity
            if (this.retailGoosEntity !== undefined && this.retailGoosEntity.goodsGroupId === 0) {
              this.retailGoosEntity.goodsGroupId = ''
            }
            this.loadPath = resBody.result.loadPath
            this.groupRetail()
            this.$nextTick(() => { // 隐藏超过n张图片时的加号
              if (document.getElementsByClassName('el-upload-list__item-actions').length >= this.picCountLimit) {
                document.getElementsByClassName('el-upload el-upload--picture-card').item(0).style.display = 'none'
              }
            })
          }
        })
      } else {
        this.groupRetail()
      }
      this.$refs.myTextEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    },
    components: {
      quillEditor
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #goodsAdd
    .el-tabs__nav
      width: 100%
      .el-tabs__item
        width: 50%
        text-align: center
    .titleCls
      text-align: center
      line-height: 60px
      width: 105px
      border-top: 2px solid #fff
    .contentCls
      width: 929px
      padding: 10px
      border-left: 2px solid #fff
      border-top: 2px solid #fff
    .bgk
      background-color: #F8F8FF
    #detailId
      .ql-editor
        min-height: 300px;
        line-height: 1
        p {
          display: block
          -webkit-margin-before: 0
          -webkit-margin-after: 0
          -webkit-margin-start: 0
          -webkit-margin-end: 0
          margin: 0
          padding: 0
          float: none
        }
        img
          border-style: none
          height: 100%
          vertical-align:top
          display: block
    .groupClass
      width: 367px
      textarea
        height: 150px
</style>
